﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Networking
{
    public class AckNackPacket : Packet
    {
        
        /// <summary>
        /// ACK or NACK
        /// </summary>
        public bool IsOK { get; private set; }

        /// <summary>
        /// Creates a new instance of AckNackPacket
        /// </summary>
        /// <param name="IsOK">If the requested protocol is OK</param>
        public AckNackPacket(bool IsOK)
            : base(PacketType.AckNack)
        {
            this.IsOK = IsOK;
        }

        /// <summary>
        /// Creates a new instance of AckNackPacket extracting all the parameters from the byte buffer
        /// </summary>
        /// <param name="buffer">The byte buffer containing the packet data</param>	
        public AckNackPacket(byte[] buffer)
            : base(PacketType.AckNack, buffer)
        {
            //
        }

        /// <summary>
        /// Serializes the packet in order to send it
        /// </summary>
        /// <returns>The bytes of the packet</returns>
        public override byte[] Serialize()
        {
            return Encoding.ASCII.GetBytes(IsOK ? "1\n" : "0\n");
        }


        /// <summary>
        /// Loads a packet from a byte buffer
        /// </summary>
        /// <param name="buffer">The data buffer</param>
        public override void Load(byte[] buffer)
        {

            if (buffer.Length != 2) throw new BufferSizeMismatchException(2);

            char c = (char)buffer[0];

            switch (c)
            {
                case '1':

                    IsOK = true;

                    break;

                case '0':

                    IsOK = false;

                    break;

                default:

                    throw new CorruptedPacketException(PacketType.AckNack, "The response should be 0 or 1");
            }

            //IsOK = ((char)buffer[0]) == '1' ? true : ((char)buffer[0]) == '0' ? false : false, throw new CorruptedPacketException(PacketType.AckNack, "The response should be 0 or 1");

        }
    }
}
